package com.zgw.fireline.design.edit;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.wb.internal.core.model.JavaInfoUtils;
import org.eclipse.wb.internal.core.model.property.GenericProperty;
import org.eclipse.wb.internal.core.model.property.Property;
import org.eclipse.wb.internal.core.model.property.editor.PropertyEditor;
import org.eclipse.wb.internal.core.model.property.editor.TextDialogPropertyEditor;
import org.eclipse.wb.internal.core.utils.ast.AstEditor;

import com.zgw.fireline.design.Model.DatasetCodeUtil;

/**
 * {@link Dataset} 的数据源提供器属性 编辑
 * */
public class DataBaseProvidePropertyEdit extends TextDialogPropertyEditor {

	// //////////////////////////////////////////////////////////////////////////
	//
	// Instance
	//
	// //////////////////////////////////////////////////////////////////////////
	public static final PropertyEditor INSTANCE = new DataBaseProvidePropertyEdit();

	private DataBaseProvidePropertyEdit() {

	}

	@Override
	protected void openDialog(Property property) throws Exception {
		IJavaProject project;

		if (property instanceof GenericProperty) {
			GenericProperty p = (GenericProperty) property;
			project = p.getJavaInfo().getEditor().getJavaProject();
			DataBaseProvideDialog dlg = new DataBaseProvideDialog(Display
					.getDefault().getActiveShell(), project);
			if (p.getValue() != null) {
				dlg.dbClass = p.getValue().getClass();
			}
			if (dlg.open() == Window.OK) {
				// 添加 dbClass 变量
				AstEditor editor = p.getJavaInfo().getEditor();
				TypeDeclaration typeDeclaration = JavaInfoUtils
						.getTypeDeclaration(p.getJavaInfo().getRootJava());
				String source = DatasetCodeUtil.prepareDBInvokeSource(
						dlg.dbClass, typeDeclaration, editor);
				p.setExpression(source, Property.UNKNOWN_VALUE);
			}
		}
	}

	@Override
	protected String getText(Property property) throws Exception {
		if (property.getValue() != null)
			return property.getValue().getClass().getSimpleName();
		return null;
	}
}
